home *** CD-ROM | disk | FTP | other *** search
/ Aminet 34 / Aminet 34 (2000)(Schatztruhe)[!][Dec 1999].iso / Aminet / dev / lang / Python152_Src.lha / Python152_Source / Python / sysmodule.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-04-27  |  18.4 KB  |  697 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* System module */
  33.  
  34. /*
  35. Various bits of information used by the interpreter are collected in
  36. module 'sys'.
  37. Function member:
  38. - exit(sts): raise SystemExit
  39. Data members:
  40. - stdin, stdout, stderr: standard file objects
  41. - modules: the table of modules (dictionary)
  42. - path: module search path (list of strings)
  43. - argv: script arguments (list of strings)
  44. - ps1, ps2: optional primary and secondary prompts (strings)
  45. */
  46.  
  47. #include "Python.h"
  48.  
  49. #include "osdefs.h"
  50.  
  51. #ifdef HAVE_UNISTD_H
  52. #include <unistd.h>
  53. #endif
  54.  
  55. #include "protos/sysmodule.h"
  56.  
  57. #ifdef MS_COREDLL
  58. extern void *PyWin_DLLhModule;
  59. /* A string loaded from the DLL at startup: */
  60. extern const char *PyWin_DLLVersionString;
  61. #endif
  62.  
  63. PyObject *
  64. PySys_GetObject(name)
  65.     char *name;
  66. {
  67.     PyThreadState *tstate = PyThreadState_Get();
  68.     PyObject *sd = tstate->interp->sysdict;
  69.     return PyDict_GetItemString(sd, name);
  70. }
  71.  
  72. FILE *
  73. PySys_GetFile(name, def)
  74.     char *name;
  75.     FILE *def;
  76. {
  77.     FILE *fp = NULL;
  78.     PyObject *v = PySys_GetObject(name);
  79.     if (v != NULL && PyFile_Check(v))
  80.         fp = PyFile_AsFile(v);
  81.     if (fp == NULL)
  82.         fp = def;
  83.     return fp;
  84. }
  85.  
  86. int
  87. PySys_SetObject(name, v)
  88.     char *name;
  89.     PyObject *v;
  90. {
  91.     PyThreadState *tstate = PyThreadState_Get();
  92.     PyObject *sd = tstate->interp->sysdict;
  93.     if (v == NULL) {
  94.         if (PyDict_GetItemString(sd, name) == NULL)
  95.             return 0;
  96.         else
  97.             return PyDict_DelItemString(sd, name);
  98.     }
  99.     else
  100.         return PyDict_SetItemString(sd, name, v);
  101. }
  102.  
  103. static PyObject *
  104. sys_exc_info(self, args)
  105.     PyObject *self;
  106.     PyObject *args;
  107. {
  108.     PyThreadState *tstate;
  109.     if (!PyArg_Parse(args, ""))
  110.         return NULL;
  111.     tstate = PyThreadState_Get();
  112.     return Py_BuildValue(
  113.         "(OOO)",
  114.         tstate->exc_type != NULL ? tstate->exc_type : Py_None,
  115.         tstate->exc_value != NULL ? tstate->exc_value : Py_None,
  116.         tstate->exc_traceback != NULL ?
  117.             tstate->exc_traceback : Py_None);
  118. }
  119.  
  120. static char exc_info_doc[] =
  121. "exc_info() -> (type, value, traceback)\n\
  122. \n\
  123. Return information about the exception that is currently being handled.\n\
  124. This should be called from inside an except clause only.";
  125.  
  126. static PyObject *
  127. sys_exit(self, args)
  128.     PyObject *self;
  129.     PyObject *args;
  130. {
  131.     /* Raise SystemExit so callers may catch it or clean up. */
  132.     PyErr_SetObject(PyExc_SystemExit, args);
  133.     return NULL;
  134. }
  135.  
  136. static char exit_doc[] =
  137. "exit([status])\n\
  138. \n\
  139. Exit the interpreter by raising SystemExit(status).\n\
  140. If the status is omitted or None, it defaults to zero (i.e., success).\n\
  141. If the status numeric, it will be used as the system exit status.\n\
  142. If it is another kind of object, it will be printed and the system\n\
  143. exit status will be one (i.e., failure).";
  144.  
  145. static PyObject *
  146. sys_settrace(self, args)
  147.     PyObject *self;
  148.     PyObject *args;
  149. {
  150.     PyThreadState *tstate = PyThreadState_Get();
  151.     if (args == Py_None)
  152.         args = NULL;
  153.     else
  154.         Py_XINCREF(args);
  155.     Py_XDECREF(tstate->sys_tracefunc);
  156.     tstate->sys_tracefunc = args;
  157.     Py_INCREF(Py_None);
  158.     return Py_None;
  159. }
  160.  
  161. static char settrace_doc[] =
  162. "settrace(function)\n\
  163. \n\
  164. Set the global debug tracing function.  It will be called on each\n\
  165. function call.  See the debugger chapter in the library manual.";
  166.  
  167. static PyObject *
  168. sys_setprofile(self, args)
  169.     PyObject *self;
  170.     PyObject *args;
  171. {
  172.     PyThreadState *tstate = PyThreadState_Get();
  173.     if (args == Py_None)
  174.         args = NULL;
  175.     else
  176.         Py_XINCREF(args);
  177.     Py_XDECREF(tstate->sys_profilefunc);
  178.     tstate->sys_profilefunc = args;
  179.     Py_INCREF(Py_None);
  180.     return Py_None;
  181. }
  182.  
  183. static char setprofile_doc[] =
  184. "setprofile(function)\n\
  185. \n\
  186. Set the profiling function.  It will be called on each function call\n\
  187. and return.  See the profiler chapter in the library manual.";
  188.  
  189. static PyObject *
  190. sys_setcheckinterval(self, args)
  191.     PyObject *self;
  192.     PyObject *args;
  193. {
  194.     PyThreadState *tstate = PyThreadState_Get();
  195.     if (!PyArg_ParseTuple(args, "i", &tstate->interp->checkinterval))
  196.         return NULL;
  197.     Py_INCREF(Py_None);
  198.     return Py_None;
  199. }
  200.  
  201. static char setcheckinterval_doc[] =
  202. "setcheckinterval(n)\n\
  203. \n\
  204. Tell the Python interpreter to check for asynchronous events every\n\
  205. n instructions.  This also affects how often thread switches occur.";
  206.  
  207. #ifdef USE_MALLOPT
  208. /* Link with -lmalloc (or -lmpc) on an SGI */
  209. #include <malloc.h>
  210.  
  211. static PyObject *
  212. sys_mdebug(self, args)
  213.     PyObject *self;
  214.     PyObject *args;
  215. {
  216.     int flag;
  217.     if (!PyArg_Parse(args, "i", &flag))
  218.         return NULL;
  219.     mallopt(M_DEBUG, flag);
  220.     Py_INCREF(Py_None);
  221.     return Py_None;
  222. }
  223. #endif /* USE_MALLOPT */
  224.  
  225. static PyObject *
  226. sys_getrefcount(self, args)
  227.     PyObject *self;
  228.     PyObject *args;
  229. {
  230.     PyObject *arg;
  231.     if (!PyArg_Parse(args, "O", &arg))
  232.         return NULL;
  233.     return PyInt_FromLong((long) arg->ob_refcnt);
  234. }
  235.  
  236. static char getrefcount_doc[] =
  237. "getrefcount(object) -> integer\n\
  238. \n\
  239. Return the current reference count for the object.  This includes the\n\
  240. temporary reference in the argument list, so it is at least 2.";
  241.  
  242. #ifdef COUNT_ALLOCS
  243. static PyObject *
  244. sys_getcounts(self, args)
  245.     PyObject *self, *args;
  246. {
  247.     extern PyObject *get_counts Py_PROTO((void));
  248.  
  249.     if (!PyArg_Parse(args, ""))
  250.         return NULL;
  251.     return get_counts();
  252. }
  253. #endif
  254.  
  255. #ifdef Py_TRACE_REFS
  256. /* Defined in objects.c because it uses static globals if that file */
  257. extern PyObject *_Py_GetObjects Py_PROTO((PyObject *, PyObject *));
  258. #endif
  259.  
  260. #ifdef DYNAMIC_EXECUTION_PROFILE
  261. /* Defined in ceval.c because it uses static globals if that file */
  262. extern PyObject *_Py_GetDXProfile Py_PROTO((PyObject *,  PyObject *));
  263. #endif
  264.  
  265. static PyMethodDef sys_methods[] = {
  266.     /* Might as well keep this in alphabetic order */
  267.     {"exc_info",    sys_exc_info, 0, exc_info_doc},
  268.     {"exit",    sys_exit, 0, exit_doc},
  269. #ifdef COUNT_ALLOCS
  270.     {"getcounts",    sys_getcounts, 0},
  271. #endif
  272. #ifdef DYNAMIC_EXECUTION_PROFILE
  273.     {"getdxp",    _Py_GetDXProfile, 1},
  274. #endif
  275. #ifdef Py_TRACE_REFS
  276.     {"getobjects",    _Py_GetObjects, 1},
  277. #endif
  278.     {"getrefcount",    sys_getrefcount, 0, getrefcount_doc},
  279. #ifdef USE_MALLOPT
  280.     {"mdebug",    sys_mdebug, 0},
  281. #endif
  282.     {"setcheckinterval",    sys_setcheckinterval, 1, setcheckinterval_doc},
  283.     {"setprofile",    sys_setprofile, 0, setprofile_doc},
  284.     {"settrace",    sys_settrace, 0, settrace_doc},
  285.     {NULL,        NULL}        /* sentinel */
  286. };
  287.  
  288. static PyObject *
  289. list_builtin_module_names()
  290. {
  291.     PyObject *list = PyList_New(0);
  292.     int i;
  293.     if (list == NULL)
  294.         return NULL;
  295.     for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
  296.         PyObject *name = PyString_FromString(
  297.             PyImport_Inittab[i].name);
  298.         if (name == NULL)
  299.             break;
  300.         PyList_Append(list, name);
  301.         Py_DECREF(name);
  302.     }
  303.     if (PyList_Sort(list) != 0) {
  304.         Py_DECREF(list);
  305.         list = NULL;
  306.     }
  307.     if (list) {
  308.         PyObject *v = PyList_AsTuple(list);
  309.         Py_DECREF(list);
  310.         list = v;
  311.     }
  312.     return list;
  313. }
  314.  
  315. /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
  316.    Two literals concatenated works just fine.  If you have a K&R compiler
  317.    or other abomination that however *does* understand longer strings,
  318.    get rid of the !!! comment in the middle and the quotes that surround it. */
  319. static char sys_doc[] =
  320. "This module provides access to some objects used or maintained by the\n\
  321. interpreter and to functions that interact strongly with the interpreter.\n\
  322. \n\
  323. Dynamic objects:\n\
  324. \n\
  325. argv -- command line arguments; argv[0] is the script pathname if known\n\
  326. path -- module search path; path[0] is the script directory, else ''\n\
  327. modules -- dictionary of loaded modules\n\
  328. exitfunc -- you may set this to a function to be called when Python exits\n\
  329. \n\
  330. stdin -- standard input file object; used by raw_input() and input()\n\
  331. stdout -- standard output file object; used by the print statement\n\
  332. stderr -- standard error object; used for error messages\n\
  333.   By assigning another file object (or an object that behaves like a file)\n\
  334.   to one of these, it is possible to redirect all of the interpreter's I/O.\n\
  335. \n\
  336. last_type -- type of last uncaught exception\n\
  337. last_value -- value of last uncaught exception\n\
  338. last_traceback -- traceback of last uncaught exception\n\
  339.   These three are only available in an interactive session after a\n\
  340.   traceback has been printed.\n\
  341. \n\
  342. exc_type -- type of exception currently being handled\n\
  343. exc_value -- value of exception currently being handled\n\
  344. exc_traceback -- traceback of exception currently being handled\n\
  345.   The function exc_info() should be used instead of these three,\n\
  346.   because it is thread-safe.\n\
  347. "
  348. #ifndef MS_WIN16
  349. /* Concatenating string here */
  350. "\n\
  351. Static objects:\n\
  352. \n\
  353. maxint -- the largest supported integer (the smallest is -maxint-1)\n\
  354. builtin_module_names -- tuple of module names built into this intepreter\n\
  355. version -- the version of this interpreter\n\
  356. copyright -- copyright notice pertaining to this interpreter\n\
  357. platform -- platform identifier\n\
  358. executable -- pathname of this Python interpreter\n\
  359. prefix -- prefix used to find the Python library\n\
  360. exec_prefix -- prefix used to find the machine-specific Python library\n\
  361. dllhandle -- [Windows only] integer handle of the Python DLL\n\
  362. winver -- [Windows only] version number of the Python DLL\n\
  363. __stdin__ -- the original stdin; don't use!\n\
  364. __stdout__ -- the original stdout; don't use!\n\
  365. __stderr__ -- the original stderr; don't use!\n\
  366. \n\
  367. Functions:\n\
  368. \n\
  369. exc_info() -- return thread-safe information about the current exception\n\
  370. exit() -- exit the interpreter by raising SystemExit\n\
  371. getrefcount() -- return the reference count for an object (plus one :-)\n\
  372. setcheckinterval() -- control how often the interpreter checks for events\n\
  373. setprofile() -- set the global profiling function\n\
  374. settrace() -- set the global debug tracing function\n\
  375. ";
  376. #endif
  377.  
  378. PyObject *
  379. _PySys_Init()
  380. {
  381.     extern int fclose Py_PROTO((FILE *));
  382.     PyObject *m, *v, *sysdict;
  383.     PyObject *sysin, *sysout, *syserr;
  384.  
  385.     m = Py_InitModule3("sys", sys_methods, sys_doc);
  386.     sysdict = PyModule_GetDict(m);
  387.  
  388.     sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
  389.     sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
  390.     syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
  391.     if (PyErr_Occurred())
  392.         return NULL;
  393.     PyDict_SetItemString(sysdict, "stdin", sysin);
  394.     PyDict_SetItemString(sysdict, "stdout", sysout);
  395.     PyDict_SetItemString(sysdict, "stderr", syserr);
  396.     /* Make backup copies for cleanup */
  397.     PyDict_SetItemString(sysdict, "__stdin__", sysin);
  398.     PyDict_SetItemString(sysdict, "__stdout__", sysout);
  399.     PyDict_SetItemString(sysdict, "__stderr__", syserr);
  400.     Py_XDECREF(sysin);
  401.     Py_XDECREF(sysout);
  402.     Py_XDECREF(syserr);
  403.     PyDict_SetItemString(sysdict, "version",
  404.                  v = PyString_FromString(Py_GetVersion()));
  405.     Py_XDECREF(v);
  406.     PyDict_SetItemString(sysdict, "hexversion",
  407.                  v = PyInt_FromLong(PY_VERSION_HEX));
  408.     Py_XDECREF(v);
  409.     PyDict_SetItemString(sysdict, "copyright",
  410.                  v = PyString_FromString(Py_GetCopyright()));
  411.     Py_XDECREF(v);
  412.     PyDict_SetItemString(sysdict, "platform",
  413.                  v = PyString_FromString(Py_GetPlatform()));
  414.     Py_XDECREF(v);
  415.     PyDict_SetItemString(sysdict, "executable",
  416.                  v = PyString_FromString(Py_GetProgramFullPath()));
  417.     Py_XDECREF(v);
  418.     PyDict_SetItemString(sysdict, "prefix",
  419.                  v = PyString_FromString(Py_GetPrefix()));
  420.     Py_XDECREF(v);
  421.     PyDict_SetItemString(sysdict, "exec_prefix",
  422.            v = PyString_FromString(Py_GetExecPrefix()));
  423.     Py_XDECREF(v);
  424.     PyDict_SetItemString(sysdict, "maxint",
  425.                  v = PyInt_FromLong(PyInt_GetMax()));
  426.     Py_XDECREF(v);
  427.     PyDict_SetItemString(sysdict, "builtin_module_names",
  428.            v = list_builtin_module_names());
  429.     Py_XDECREF(v);
  430. #ifdef MS_COREDLL
  431.     PyDict_SetItemString(sysdict, "dllhandle",
  432.                  v = PyInt_FromLong((int)PyWin_DLLhModule));
  433.     Py_XDECREF(v);
  434.     PyDict_SetItemString(sysdict, "winver",
  435.                  v = PyString_FromString(PyWin_DLLVersionString));
  436.     Py_XDECREF(v);
  437. #endif
  438.     if (PyErr_Occurred())
  439.         return NULL;
  440.     return m;
  441. }
  442.  
  443. static PyObject *
  444. makepathobject(path, delim)
  445.     char *path;
  446.     int delim;
  447. {
  448.     int i, n;
  449.     char *p;
  450.     PyObject *v, *w;
  451.     
  452.     n = 1;
  453.     p = path;
  454.     while ((p = strchr(p, delim)) != NULL) {
  455.         n++;
  456.         p++;
  457.     }
  458.     v = PyList_New(n);
  459.     if (v == NULL)
  460.         return NULL;
  461.     for (i = 0; ; i++) {
  462.         p = strchr(path, delim);
  463.         if (p == NULL)
  464.             p = strchr(path, '\0'); /* End of string */
  465.         w = PyString_FromStringAndSize(path, (int) (p - path));
  466.         if (w == NULL) {
  467.             Py_DECREF(v);
  468.             return NULL;
  469.         }
  470.         PyList_SetItem(v, i, w);
  471.         if (*p == '\0')
  472.             break;
  473.         path = p+1;
  474.     }
  475.     return v;
  476. }
  477.  
  478. void
  479. PySys_SetPath(path)
  480.     char *path;
  481. {
  482.     PyObject *v;
  483.     if ((v = makepathobject(path, DELIM)) == NULL)
  484.         Py_FatalError("can't create sys.path");
  485.     if (PySys_SetObject("path", v) != 0)
  486.         Py_FatalError("can't assign sys.path");
  487.     Py_DECREF(v);
  488. }
  489.  
  490. static PyObject *
  491. makeargvobject(argc, argv)
  492.     int argc;
  493.     char **argv;
  494. {
  495.     PyObject *av;
  496.     if (argc <= 0 || argv == NULL) {
  497.         /* Ensure at least one (empty) argument is seen */
  498.         static char *empty_argv[1] = {""};
  499.         argv = empty_argv;
  500.         argc = 1;
  501.     }
  502.     av = PyList_New(argc);
  503.     if (av != NULL) {
  504.         int i;
  505.         for (i = 0; i < argc; i++) {
  506.             PyObject *v = PyString_FromString(argv[i]);
  507.             if (v == NULL) {
  508.                 Py_DECREF(av);
  509.                 av = NULL;
  510.                 break;
  511.             }
  512.             PyList_SetItem(av, i, v);
  513.         }
  514.     }
  515.     return av;
  516. }
  517.  
  518. void
  519. PySys_SetArgv(argc, argv)
  520.     int argc;
  521.     char **argv;
  522. {
  523.     PyObject *av = makeargvobject(argc, argv);
  524.     PyObject *path = PySys_GetObject("path");
  525.     if (av == NULL)
  526.         Py_FatalError("no mem for sys.argv");
  527.     if (PySys_SetObject("argv", av) != 0)
  528.         Py_FatalError("can't assign sys.argv");
  529.     if (path != NULL) {
  530.         char *argv0 = argv[0];
  531.         char *p = NULL;
  532.         int n = 0;
  533.         PyObject *a;
  534. #ifdef HAVE_READLINK
  535.         char link[MAXPATHLEN+1];
  536.         char argv0copy[2*MAXPATHLEN+1];
  537.         int nr = 0;
  538.         if (argc > 0 && argv0 != NULL)
  539.             nr = readlink(argv0, link, MAXPATHLEN);
  540.         if (nr > 0) {
  541.             /* It's a symlink */
  542.             link[nr] = '\0';
  543.             if (link[0] == SEP)
  544.                 argv0 = link; /* Link to absolute path */
  545.             else if (strchr(link, SEP) == NULL)
  546.                 ; /* Link without path */
  547.             else {
  548.                 /* Must join(dirname(argv0), link) */
  549.                 char *q = strrchr(argv0, SEP);
  550.                 if (q == NULL)
  551.                     argv0 = link; /* argv0 without path */
  552.                 else {
  553.                     /* Must make a copy */
  554.                     strcpy(argv0copy, argv0);
  555.                     q = strrchr(argv0copy, SEP);
  556.                     strcpy(q+1, link);
  557.                     argv0 = argv0copy;
  558.                 }
  559.             }
  560.         }
  561. #endif /* HAVE_READLINK */
  562. #if SEP == '\\' /* Special case for MS filename syntax */
  563.         if (argc > 0 && argv0 != NULL) {
  564.             char *q;
  565.             p = strrchr(argv0, SEP);
  566.             /* Test for alternate separator */
  567.             q = strrchr(p ? p : argv0, '/');
  568.             if (q != NULL)
  569.                 p = q;
  570.             if (p != NULL) {
  571.                 n = p + 1 - argv0;
  572.                 if (n > 1 && p[-1] != ':')
  573.                     n--; /* Drop trailing separator */
  574.             }
  575.         }
  576. #else /* All other filename syntaxes */
  577.         if (argc > 0 && argv0 != NULL)
  578.             p = strrchr(argv0, SEP);
  579.         if (p != NULL) {
  580.             n = p + 1 - argv0;
  581. #if SEP == '/' /* Special case for Unix filename syntax */
  582.             if (n > 1)
  583.                 n--; /* Drop trailing separator */
  584. #endif /* Unix */
  585.         }
  586. #ifdef _AMIGA
  587.         else
  588.         {
  589.             /* check for absolute paths on Amiga */
  590.             if(argc>0 && argv0!=NULL) p=strrchr(argv0,':');
  591.             if(p!=NULL)     n=p+1-argv0;
  592.         }
  593. #endif /* _AMIGA */
  594. #endif /* All others */
  595.         a = PyString_FromStringAndSize(argv0, n);
  596.         if (a == NULL)
  597.             Py_FatalError("no mem for sys.path insertion");
  598.         if (PyList_Insert(path, 0, a) < 0)
  599.             Py_FatalError("sys.path.insert(0) failed");
  600.         Py_DECREF(a);
  601.     }
  602.     Py_DECREF(av);
  603. }
  604.  
  605.  
  606. /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
  607.    Adapted from code submitted by Just van Rossum.
  608.  
  609.    PySys_WriteStdout(format, ...)
  610.    PySys_WriteStderr(format, ...)
  611.  
  612.       The first function writes to sys.stdout; the second to sys.stderr.  When
  613.       there is a problem, they write to the real (C level) stdout or stderr;
  614.       no exceptions are raised.
  615.  
  616.       Both take a printf-style format string as their first argument followed
  617.       by a variable length argument list determined by the format string.
  618.  
  619.       *** WARNING ***
  620.  
  621.       The format should limit the total size of the formatted output string to
  622.       1000 bytes.  In particular, this means that no unrestricted "%s" formats
  623.       should occur; these should be limited using "%.<N>s where <N> is a
  624.       decimal number calculated so that <N> plus the maximum size of other
  625.       formatted text does not exceed 1000 bytes.  Also watch out for "%f",
  626.       which can print hundreds of digits for very large numbers.
  627.  
  628.  */
  629.  
  630. static void
  631. mywrite(name, fp, format, va)
  632.     char *name;
  633.     FILE *fp;
  634.     const char *format;
  635.     va_list va;
  636. {
  637.     PyObject *file;
  638.     PyObject *error_type, *error_value, *error_traceback;
  639.  
  640.     PyErr_Fetch(&error_type, &error_value, &error_traceback);
  641.     file = PySys_GetObject(name);
  642.     if (file == NULL || PyFile_AsFile(file) == fp)
  643.         vfprintf(fp, format, va);
  644.     else {
  645.         char buffer[1001];
  646.         if (vsprintf(buffer, format, va) >= sizeof(buffer))
  647.             Py_FatalError("PySys_WriteStdout/err: buffer overrun");
  648.         if (PyFile_WriteString(buffer, file) != 0) {
  649.             PyErr_Clear();
  650.             fputs(buffer, fp);
  651.         }
  652.     }
  653.     PyErr_Restore(error_type, error_value, error_traceback);
  654. }
  655.  
  656. void
  657. #ifdef HAVE_STDARG_PROTOTYPES
  658. PySys_WriteStdout(const char *format, ...)
  659. #else
  660. PySys_WriteStdout(va_alist)
  661.     va_dcl
  662. #endif
  663. {
  664.     va_list va;
  665.  
  666. #ifdef HAVE_STDARG_PROTOTYPES
  667.     va_start(va, format);
  668. #else
  669.     char *format;
  670.     va_start(va);
  671.     format = va_arg(va, char *);
  672. #endif
  673.     mywrite("stdout", stdout, format, va);
  674.     va_end(va);
  675. }
  676.  
  677. void
  678. #ifdef HAVE_STDARG_PROTOTYPES
  679. PySys_WriteStderr(const char *format, ...)
  680. #else
  681. PySys_WriteStderr(va_alist)
  682.     va_dcl
  683. #endif
  684. {
  685.     va_list va;
  686.  
  687. #ifdef HAVE_STDARG_PROTOTYPES
  688.     va_start(va, format);
  689. #else
  690.     char *format;
  691.     va_start(va);
  692.     format = va_arg(va, char *);
  693. #endif
  694.     mywrite("stderr", stderr, format, va);
  695.     va_end(va);
  696. }
  697.